/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.business.fee.core.service.processor.rule;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import info.peigen.hotpot.business.account.core.domain.account.Account;
import info.peigen.hotpot.business.fee.core.domain.FeeRule;
import info.peigen.hotpot.business.fee.core.service.processor.base.AbstractFeeServiceProcessor;
import info.peigen.hotpot.business.fee.facade.command.order.rule.FeeRuleModifyOrder;
import info.peigen.hotpot.common.core.result.ResultCode;
import info.peigen.hotpot.common.service.base.exception.BusinessException;
import info.peigen.hotpot.common.service.base.processor.Processor;
import info.peigen.hotpot.common.service.base.processor.ProcessorServiceContext;
import org.noear.solon.annotation.Component;


/**
 * <b>(FeeRuleModifyProcessor)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/6/1
 */
@Component
public class FeeRuleModifyProcessor extends AbstractFeeServiceProcessor implements Processor {
    @Override
    public Integer level() {
        return 20;
    }

    @Override
    public void execute(ProcessorServiceContext serviceContext) {
        FeeRuleModifyOrder order = (FeeRuleModifyOrder) serviceContext.getOrder();
        FeeRule            rule  = feeRepository.activeFeeRule(order.getRuleId());

        if (ObjectUtil.isNotNull(order.getMethod())) {
            rule.setMethod(order.getMethod());
        }

        if (StrUtil.isNotEmpty(order.getContext())) {
            rule.setContext(order.getContext());
        }

        if (StrUtil.isNotEmpty(order.getBillingAccountId())) {
            Account billingAccount = accountRepository.active(order.getBillingAccountId());
            Assert.notNull(billingAccount, () -> new BusinessException(ResultCode.FAILURE, "收费规则[计费]客户不得为空![billingAccountId=]" + order.getBillingAccountId()));
            rule.setBillingAccount(billingAccount);
        }

        if (StrUtil.isNotEmpty(order.getPayerAccountId())) {
            Account payerAccount = accountRepository.active(order.getPayerAccountId());
            Assert.notNull(payerAccount, () -> new BusinessException(ResultCode.FAILURE, "收费规则[付费]客户不得为空![payerAccountId=]" + order.getPayerAccountId()));
            rule.setPayerAccount(payerAccount);
        }

        if (StrUtil.isNotEmpty(order.getPayeeAccountId())) {
            Account payeeAccount = accountRepository.active(order.getPayeeAccountId());
            Assert.notNull(payeeAccount, () -> new BusinessException(ResultCode.FAILURE, "收费规则[收费]客户不得为空![payeeAccountId=]" + order.getPayeeAccountId()));
            rule.setPayeeAccount(payeeAccount);
        }

        if (StrUtil.isNotEmpty(order.getMemo())) {
            rule.setMemo(order.getMemo());
        }
        serviceContext.setDomain(rule);
        serviceContext.getResult().setSuccessNotFee();
    }
}
